import { saveReceipt } from '@/services/api/api-pressconference';
import { PlusOutlined } from '@ant-design/icons';
import {
  ActionType,
  DrawerForm,
  EditableProTable,
  ProColumns,
  ProFormInstance,
  ProFormTextArea,
} from '@ant-design/pro-components';
import { Alert, Button, message, Tag } from 'antd';
import { useRef, useState } from 'react';
import { useAccess } from 'umi';

interface UpdateReceiptProps {
  receipt: PressconferenceData.ReceiptPage;
  onSave: () => void;
}

const UpdateReceipt: React.FC<UpdateReceiptProps> = ({ receipt, onSave }) => {
  const access = useAccess();
  const formRef = useRef<ProFormInstance>();

  const actionRef = useRef<ActionType>();

  const [dataSource, setDataSource] = useState<any>(receipt?.participates);
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]);

  const columns: ProColumns<PressconferenceData.ReceiptParticipatePage>[] = [
    {
      title: (
        <span
          style={{
            color: '#99a3b7',
            fontSize: 12,
            textAlign: 'center',
            fontWeight: 'normal',
          }}
        >
          姓名
        </span>
      ),
      dataIndex: 'name',
      align: 'center',
    },
    {
      title: (
        <span
          style={{
            color: '#99a3b7',
            fontSize: 12,
            textAlign: 'center',
            fontWeight: 'normal',
          }}
        >
          电话
        </span>
      ),
      dataIndex: 'phone',
      align: 'center',
    },

    {
      title: (
        <span
          style={{
            color: '#99a3b7',
            fontSize: 12,
            textAlign: 'center',
            fontWeight: 'normal',
          }}
        >
          描述
        </span>
      ),
      dataIndex: 'describes',
      align: 'center',
    },
    {
      title: '操作',
      valueType: 'option',
      width: 100,
      render: (text, record, _, action) => [
        <a
          key="editable"
          onClick={() => {
            action?.startEditable?.(record.id);
          }}
        >
          编辑
        </a>,
        <a
          key="delete"
          onClick={() => {
            setDataSource(dataSource.filter((item) => item.id !== record.id));
          }}
        >
          删除
        </a>,
      ],
    },
  ];

  return (
    <DrawerForm
      title="编辑回复"
      trigger={
        <Tag color="blue" style={{ marginLeft: 5 }}>
          编辑
        </Tag>
      }
      layout="horizontal"
      formRef={formRef}
      autoFocusFirstInput
      drawerProps={{
        size: 'large',
        forceRender: true,
        destroyOnClose: true,
        width: 800,
      }}
      initialValues={{
        assignType: '4',
      }}
      onFinish={async (values) => {
        if (
          values.content === undefined ||
          values.content.length === 0 ||
          values.content.trim() === ''
        ) {
          message.warning('请输入回执内容');
          return;
        }

        if (editableKeys.length > 0) {
          message.warning('请保存参会人员名单');
          return;
        }

        if (dataSource.length == 0) {
          message.warning('请添加参会人员信息');
          return;
        }

        const response = await saveReceipt({
          recordId: receipt?.recordId,
          ...values,
          participates: dataSource,
        });
        if (response.code === 0) {
          message.success('提交成功');
          onSave();
          return true;
        } else {
          return false;
        }
      }}
    >
      <>
        <ProFormTextArea
          name="content"
          required
          label=""
          initialValue={receipt?.content}
          placeholder="请输入回执"
          fieldProps={{
            rows: 10,
            count: {
              show: true,
            },
          }}
        />
        <EditableProTable<PressconferenceData.ReceiptParticipatePage>
          columns={columns}
          actionRef={actionRef}
          rowKey="id"
          dateFormatter="id"
          defaultSize={'small'}
          pagination={false}
          search={false}
          options={false}
          ghost
          headerTitle={
            <Alert
              message="参会人员"
              type="info"
              showIcon
              style={{
                fontSize: 12,
              }}
            />
          }
          value={dataSource}
          onChange={setDataSource}
          toolBarRender={() => [
            <Button
              key="button"
              icon={<PlusOutlined />}
              onClick={() => {
                actionRef.current?.addEditRecord({
                  id: (Math.random() * 1000000).toFixed(0),
                  name: '',
                });
              }}
              type="primary"
            >
              添加参会人员
            </Button>,
          ]}
          recordCreatorProps={false}
          editable={{
            type: 'multiple',
            editableKeys,
            actionRender: (row, config, defaultDom) => {
              return [defaultDom.save, defaultDom.cancel];
            },
            onChange: setEditableRowKeys,
          }}
        />
      </>
    </DrawerForm>
  );
};

export default UpdateReceipt;
